package org.yaukie.frame.autocode.controller;

import cn.hutool.core.io.FileUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.yaukie.base.annotation.EnablePage;
import org.yaukie.base.annotation.LogAround;
import org.yaukie.base.annotation.OperLog;
import org.yaukie.base.config.UniformReponseHandler;
import org.yaukie.base.constant.BaseResult;
import org.yaukie.base.constant.BaseResultConstant;
import org.yaukie.base.constant.PageResult;
import org.yaukie.base.constant.SysConstant;
import org.yaukie.base.core.controller.BaseController;
import org.yaukie.base.exception.UserDefinedException;
import org.yaukie.frame.autocode.model.XDatabase;
import org.yaukie.frame.autocode.model.XDatabaseExample;
import org.yaukie.frame.autocode.model.XRepository;
import org.yaukie.frame.autocode.model.XRepositoryExample;
import org.yaukie.frame.autocode.service.api.XDatabaseService;
import org.yaukie.frame.autocode.service.api.XRepositoryService;
import org.yaukie.xtl.KettleUtil;
import org.yaukie.xtl.cons.Constant;
import org.yaukie.xtl.repo.RepositoryTree;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;

/**
 * @author: yuenbin
 * @create: 2021/01/29 19/28/716
 **/
@RestController
@RequestMapping(value = "/op/file/")
@Api(value = "文件控制器", description = "文件控制器")
@Slf4j
public class XFileController extends BaseController {

    @Autowired
    private XDatabaseService xDatabaseService;

    @Autowired
    private XRepositoryService xRepositoryService;


    @RequestMapping(value = "/testApi", method = RequestMethod.POST)
    @ApiOperation("测试数据库连接")
    @LogAround("测试数据连接")
    public BaseResult testConnection(
            @ApiParam(name = "ddDatasourceDto", value = "数据源对象", required = true)
            @RequestBody XDatabase xDatabase) {

        return BaseResult.success();
    }

    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ApiOperation("上传文件")
    @LogAround("上传文件")
    public void fileUpload(MultipartFile file,String id,String currentName) throws IOException {
        String pid = id.replaceAll("@","").replaceAll("/","");
        System.out.println(file.getOriginalFilename());
        XRepositoryExample teammemberExample = new XRepositoryExample();
        XRepositoryExample.Criteria criteria = teammemberExample.createCriteria();
        criteria.andRepoIdEqualTo(pid);

        List<XRepository> list = this.xRepositoryService.selectByExample(teammemberExample);
        XRepository xRepository =list.get(0);
        String path =xRepository.getBaseDir();
        if (path==currentName){
            FileUtil.writeBytes(file.getBytes(),path+File.separator+file.getOriginalFilename());
        }else {
            FileUtil.writeBytes(file.getBytes(),path+File.separator+currentName+File.separator+file.getOriginalFilename());

        }

    }

    @RequestMapping(value = "/deleteFile", method = RequestMethod.GET)
    @ApiOperation("删除文件")
    @LogAround("删除文件")
    public void deleteFile(@RequestParam("id") String id,String currentName,String file)throws IOException {
        String pid = id.replaceAll("@","").replaceAll("/","");
        System.out.println(file);
        XRepositoryExample teammemberExample = new XRepositoryExample();
        XRepositoryExample.Criteria criteria = teammemberExample.createCriteria();
        criteria.andRepoIdEqualTo(pid);

        List<XRepository> list = this.xRepositoryService.selectByExample(teammemberExample);
        XRepository xRepository =list.get(0);
        String path =xRepository.getBaseDir();
        if (path==currentName){
            FileUtil.del(path+File.separator+file);
        }else {
            FileUtil.del(path+File.separator+currentName+File.separator+file);

        }
    }

    @RequestMapping(value = "/mkDirs", method = RequestMethod.GET)
    @ApiOperation("添加文件")
    @LogAround("添加文件")
    public void createFile(String path,String name) {
        String splicing = path.replaceAll("@", "").replaceAll("/", "");
        XRepositoryExample teammemberExample = new XRepositoryExample();
        XRepositoryExample.Criteria criteria = teammemberExample.createCriteria();
        String allPath;
        if (!"".equals(path)) {

            Pattern pattern = Pattern.compile("[0-9]+");
            Matcher matcher = pattern.matcher((CharSequence) path);
            boolean result = matcher.matches();
            if (!result) {
                criteria.andRepoNameEqualTo(splicing);
                List<XRepository> list = this.xRepositoryService.selectByExample(teammemberExample);
                XRepository xRepository = list.get(0);
                allPath = xRepository.getBaseDir() + File.separator + name;

            } else {
                criteria.andRepoIdEqualTo(splicing);

                List<XRepository> list = this.xRepositoryService.selectByExample(teammemberExample);
                XRepository xRepository = list.get(0);
                allPath = xRepository.getBaseDir() + File.separator + name;
            }
            FileUtil.mkdir(allPath);
        }
    }
}
